import awardBlankSheet.AwardBlankGrid;
import awardBlankSheet.PendingRequest;

import common.Mask;
import common.commonFunction;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumn;
import mx.controls.advancedDataGridClasses.AdvancedDataGridColumnGroup;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;

public var userId:String;
public var displayType:String;//="I";
public var buttonPressed:String=null;
private var employeeCode:String=null;
private var programCourseKey:String=null;
[Bindable]
private var entityTypeXml:XML;
[Bindable]
private var entityXml:XML;
[Bindable]
private var programXml:XML;
[Bindable]
private var branchXml:XML;
[Bindable]
private var specXml:XML;
[Bindable]
private var semXml:XML;
[Bindable]
private var courseXml:XML;
[Bindable]
private var componentXml:XML;
[Bindable]
private var studentXml:XML;
[Bindable]
private var marksXml:XML;
[Bindable]
private var ruleXml:XML;
[Bindable]
private var employeeXml:XML;
[Bindable]
private var keyXml:XML;
private var componentAC:ArrayCollection=new ArrayCollection();
private var studentListAC:ArrayCollection=new ArrayCollection();  
private var studentMarksListAC:ArrayCollection=new ArrayCollection(); 

[Bindable]public var param:Object={};	
		  
	/*
	 * Function for saving the marks/grades of students
	 */	
	public function saveMarks():void
	{
		var gridData:ArrayCollection=commonFunction.getAdvancedDataGridRowData(awardSheetGrid);
		var s:String="";
		for each(var o:Object in gridData){
			for(var v:String in o){
    			if((v!="rollNumber")&&(v!="studentName")&&(v!="totalMarks")&&(v!=o[v]+"idType")){
    				s+=o["rollNumber"]+"|"+v+"|"+componentXml.component.(evaluationId==v).idType+"|"+o[v]+"|"+o["totalMarks"]+";";
    			}
    		}   		
		}
	    		
//		Alert.show(s);
	 	var params:Object=new Object();
		params["userId"]=userId;   		
		params["courseCode"]=courseCode;
		params["startDate"]=semXml.root.(name==semesterCombo.selectedLabel).startDate;
		params["endDate"]=semXml.root.(name==semesterCombo.selectedLabel).endDate;
    	params["programCourseKey"]=programCourseKey;
    	params["employeeCode"]=employeeCode;  
		params["displayType"]=displayType;
    	params["data"]=s;
    	Mask.show("Wait....");	    		
		httpSaveSheet.send(params);
	}
	    	

	/**
	function for getting entity type list
	*/
	public function getEntityTypeList():void{
		var params:Object=new Object();
		params["userId"]=userId;
		httpEntityType.send(params);
		httpEmployeeCode.send();
	}

	private function faultHandler_EntityType(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_EntityType(event:ResultEvent):void{
		entityTypeXml=event.result as XML;
	   	var entityTypeAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in entityTypeXml.entityTypeList){
	   		entityTypeAC.addItem({entity_id:object.entity_id,entity_name:object.entity_name,level:object.level});
	   	}
	  	entityTypeCombo.dataProvider=entityTypeAC;
	 }
 
 
 	private function faultHandler_EmployeeCode(event:FaultEvent):void{
         Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
    }

	private function resultHandler_EmployeeCode(event:ResultEvent):void{
		employeeXml=event.result as XML;
		employeeCode=employeeXml.root.code;
		var params:Object=new Object();
	 	params["userId"]=userId;
	    params["employeeCode"]=employeeCode;
		params["displayType"]=displayType; // added by ankit
		httpPendingRequests.send(params);
	 }

	private function resultHandler_key(event:ResultEvent):void{
		keyXml=event.result as XML;
		programCourseKey=keyXml.root.code;
	}
 
 
	/**
	function for getting entity list
	*/
	public function getEntityList():void{
		var params:Object=new Object();
		params["userId"]=userId;
		params["entityType"]=entityTypeXml.entityTypeList.(entity_name==entityTypeCombo.selectedLabel).entity_id;
		httpEntityList.send(params);
	}

	private function faultHandler_EntityList(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_EntityList(event:ResultEvent):void{
		entityXml=event.result as XML;
	   	var entityAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in entityXml.root){
	   		entityAC.addItem({name:object.name,code:object.code});
	   	}
	  	entityNameCombo.dataProvider=entityAC;
	}
 
	/**
	function for getting program list
	*/
	public function getProgramList():void{
		var params:Object=new Object();
		params["entityId"]=entityXml.root.(name==entityNameCombo.selectedLabel).code;
		httpProgramList.send(params);
	}

	private function faultHandler_ProgramList(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_ProgramList(event:ResultEvent):void{
		programXml=event.result as XML;
	   	var programAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in programXml.root){
	   		programAC.addItem({name:object.name,code:object.code});
	   	}
	  	programCombo.dataProvider=programAC;
	}
 
 
	/**
	function for getting Branch list
	*/
	public function getBranchList():void{
		var params:Object=new Object();
		params["entityId"]=entityXml.root.(name==entityNameCombo.selectedLabel).code;
		params["userId"]=userId;
		params["programId"]=programXml.root.(name==programCombo.selectedLabel).code;
		httpBranchList.send(params);
	}

	private function faultHandler_BranchList(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_BranchList(event:ResultEvent):void{
		branchXml=event.result as XML;
	   	var branchAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in branchXml.root){
	   		branchAC.addItem({name:object.name,code:object.code});
	   	}
	  	branchCombo.dataProvider=branchAC;
	 }
 
	/*
	function for getting specialization list
	*/
	public function getSpecList():void{
		var params:Object=new Object();
		params["entityId"]=entityXml.root.(name==entityNameCombo.selectedLabel).code;
		params["userId"]=userId;
		params["programId"]=programXml.root.(name==programCombo.selectedLabel).code;
		params["branchCode"]=branchXml.root.(name==branchCombo.selectedLabel).code;
		httpSpecList.send(params);
	}

	private function faultHandler_SpecList(event:FaultEvent):void{
	         mx.controls.Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	/**
		result handlers for getting specialization list
	*/
	private function resultHandler_SpecList(event:ResultEvent):void{
		specXml=event.result as XML;
	   	var specAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in specXml.root){
	   		specAC.addItem({name:object.name,code:object.code});
	   	}
	  	specializationCombo.dataProvider=specAC;
	} 

	/**
	function for getting specialization list
	*/
	public function getSemList():void{
		var params:Object=new Object();
		params["userId"]=userId;
		params["programId"]=programXml.root.(name==programCombo.selectedLabel).code;
		httpSemesterList.send(params);
	}

	private function faultHandler_SemList(event:FaultEvent):void{
	         mx.controls.Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_SemList(event:ResultEvent):void{
		semXml=event.result as XML;
	  	var semAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in semXml.root){
	   		semAC.addItem({name:object.name,code:object.code,startDate:object.startDate,endDate:object.endDate});
	   	}
	  	semesterCombo.dataProvider=semAC;
	}
	  
	/**
	function for getting course list
	*/
	public function getCourseList():void{
		
		if(Validator.validateAll([entityTypeValidator,entityNameValidator,programValidator,branchValidator,specializationValidator,
					                          semesterValidator]).length==0)
		{
		var params:Object=new Object();
		params["programId"]=programXml.root.(name==programCombo.selectedLabel).code;
		params["branchCode"]=branchXml.root.(name==branchCombo.selectedLabel).code;
		params["specCode"]=specXml.root.(name==specializationCombo.selectedLabel).code;
		params["semesterCode"]=semXml.root.(name==semesterCombo.selectedLabel).code;
		httpCourseList.send(params);
		}
	}

	private function faultHandler_CourseList(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}

	private function resultHandler_CourseList(event:ResultEvent):void{
		courseXml=event.result as XML;
	   	var courseAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in courseXml.root){
	   		courseAC.addItem({name:object.name,code:object.code});
	   	}
	  	courseCodeCombo.dataProvider=courseAC;
	}
 
	/**
	 * function for setting course name in text box
	 */
	private function setCourseName():void{
		courseNameField.text=courseXml.root.(code==courseCodeCombo.selectedLabel).name;
	}
 
	/**
	function for getting evaluation components
	*/
	public function getEvaluationComponents():void{
		
	//	if(Validator.validateAll([courseCodeValidator]).length==0)
	//	{
			var params:Object=new Object();
			params["programId"]=programId;
			params["courseCode"]=courseCode;
			params["userId"]=userId;
			params["displayType"]=displayType;
			httpComponentList.send(params);
	//	}
	}

	private function faultHandler_Component(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_Component(event:ResultEvent):void{
		componentXml=event.result as XML;
//		Alert.show(componentXml+"");
	   	componentAC.removeAll();
		var flag:Boolean=true;
	   	for each (var object:Object in componentXml.component){
	   		componentAC.addItem({evaluationId:object.evaluationId,group:object.group,
	   		rule:object.rule,idType:object.idType,displayType:object.displayType,maximumMarks:object.maximumMarks});
	   	}
			
		param["userId"]=userId;
		param["programId"]=programId;
		param["branchCode"]=branchId;
		param["specCode"]=specializationId;
		param["semesterCode"]=semesterId;
		param["courseCode"]=courseCode;
		param["displayType"]=displayType;
		
		if(buttonPressed=='PL'){
			param["startDate"]=sessionStartDate;
			param["endDate"]=sessionEndDate;
		}else{
			param["startDate"]=semXml.root.(name==semesterCombo.selectedLabel).startDate;
			param["endDate"]=semXml.root.(name==semesterCombo.selectedLabel).endDate;	
		}
		param["buttonPressed"]=buttonPressed;
		httpProgramCourseKey.send(param);
		httpRules.send(param);
		httpStudentList.send(param);
	 }
 
	private function getStudentMarks():void{
	 	 httpStudentMarksList.send(param);
	}
 
	private function faultHandler_Student(event:FaultEvent):void{
    	Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
    }
    
	private function resultHandler_Student(event:ResultEvent):void{
		studentXml=event.result as XML;
	   	Alert.show(studentXml+"");
	  	getStudentMarks();
	}
	
// var combined:XML;
 
	private function faultHandler_StudentMarks(event:FaultEvent):void{
    	Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
    }
	
	private function resultHandler_StudentMarks(event:ResultEvent):void{
 		marksXml=event.result as XML;
// 		Alert.show(marksXml+"Student MArks ");
 
		studentMarksListAC.removeAll();
		var abc:ArrayCollection=new ArrayCollection();

   		for each (var obj1:Object in studentXml.student){
   			var resultObj:Object=new Object();
   			resultObj["rollNumber"]=obj1.rollNumber;
   			resultObj["studentName"]=obj1.studentName;
   			
   			
   			for each(var obj2:Object in marksXml.marks){
   				if(obj1.rollNumber==obj2.rollNumber){
   					var cValue:String="";
   					
   					if(obj2.marks!=""){
   						cValue=obj2.marks;
   					}else if(obj2.grades!=""){
   						cValue=obj2.grades;
   					}else{
   						cValue=obj2.passfail;
   					}

   					resultObj[obj2.evaluationId]=cValue;
   					
   					resultObj["totalExternal"]=obj2.totalExternal;
   					resultObj["totalInternal"]=obj2.totalInternal;
   				}
   			}
   			abc.addItem(resultObj);
   		}
   		
  		if(buttonPressed=="PL"){
  			createPopup(abc);
  		}
  		else
  		{
  			createGrid(abc);
  		}
	}
 
 
	private function faultHandler_rule(event:FaultEvent):void{
		Alert.show(event.fault.message,commonFunction.getMessages('error'),4,null,null,errorIcon);
	}
	
	private function resultHandler_rule(event:ResultEvent):void{
		ruleXml=event.result as XML;
	   	var ruleAC:ArrayCollection=new ArrayCollection();
		var flag:Boolean=true;
	   	for each (var object:Object in ruleXml.root){
	   		ruleAC.addItem({name:object.name,code:object.code});
	   	}   	
	   	// here group is code and rule is name
	 }  
 
 	 /**
	 * function to create grid
	 */
	 private function createGrid(dataArray:ArrayCollection):void {
	 	var colmns: Array = new Array;
		var rollNoColmn:AdvancedDataGridColumn=new AdvancedDataGridColumn;
		rollNoColmn.headerText=commonFunction.getConstants('rollNo');
		rollNoColmn.width=100;
		rollNoColmn.editable=false;
		rollNoColmn.dataField='rollNumber';
		
		var nameColmn:AdvancedDataGridColumn=new AdvancedDataGridColumn;
		nameColmn.headerText=commonFunction.getConstants('studentName');
		nameColmn.width=150;
		nameColmn.editable=false;
		nameColmn.dataField='studentName';
		
		colmns.push(rollNoColmn);
		colmns.push(nameColmn);
			                
		var temp:Array=new Array();
		var w:int=320;
							
		for each(var obj1:Object in componentAC)
		{
			var groupName:String=obj1.group;
			if(temp.indexOf(groupName)<0)
			{
				temp.push(groupName);
				var colmnGroup:AdvancedDataGridColumnGroup=new AdvancedDataGridColumnGroup;
				colmnGroup.headerText=groupName;
				for each(var obj2:Object in componentAC){
					if(obj2.group==groupName){
						var colmn:AdvancedDataGridColumn=new AdvancedDataGridColumn;
						colmn.headerText=obj2.evaluationId+"\n"+obj2.maximumMarks;
		                colmn.sortable=false;
		                colmn.dataField=obj2.evaluationId;
		                colmn.dataTipField=obj2.evaluationId;
		                
		                switch(obj2.idType+"")
		                {
		                	case 'GR':
		                	    colmn.width=51;
		                        colmn.editorDataField='grValue';					                        
		                        colmn.itemEditor=new ClassFactory(GRRenderer);
		                        break;
		                	case 'MK':
							    colmn.width=56;
							    colmn.editorDataField='mkValue';
							    MKRenderer.maxVal=int(obj2.maximumMarks);
							    colmn.itemEditor=new ClassFactory(MKRenderer);
							    colmnGroup.children.push(colmn);
								w+=int(colmn.width);
								if(displayType=='E'){
							    	var wColmn:AdvancedDataGridColumn=new AdvancedDataGridColumn;
									wColmn.width=-1;		
									wColmn.sortable=false;
									wColmn.editable=false;
									wColmn.headerText=obj2.evaluationId+"(In Words)";
							        wColmn.width=120;
							        wColmn.dataField=obj2.evaluationId+"iw";
							        wColmn.labelFunction=getInWords;
							        colmnGroup.children.push(wColmn);
									w+=int(wColmn.width);
							    }
								break;
		                	case 'PF':
		                		colmn.width=61;
		                		colmn.editorDataField='selectedVal';
		                        colmn.itemEditor=new ClassFactory(PFRenderer);
		                        colmnGroup.children.push(colmn);
		                		w+=int(colmn.width);
		                        break;
		                   } //end of switch
		             }// end of if 
		    	}// end of loop
		    	colmns.push(colmnGroup);
	    	}
    	}
		
		if(displayType=='I' || displayType=='R'){
			var totalMarksColmn:AdvancedDataGridColumn=new AdvancedDataGridColumn;
			totalMarksColmn.headerText=commonFunction.getConstants('totalMarks');
			totalMarksColmn.width=100;
			totalMarksColmn.editable=false;
			totalMarksColmn.dataField='totalMarks';
			totalMarksColmn.labelFunction=getTotal;
			colmns.push(totalMarksColmn);
			w=w+100;
		}
		awardSheetGrid.groupedColumns = colmns;
		awardSheetGrid.width=w;
		awardSheetGrid.dataProvider=dataArray;
		
		awardSheetCanvas.visible=true;
		if(w<400){
			awardSheetCanvas.width=420;
		}
		else{
			awardSheetCanvas.width=w+20;
		}
		if(w>=800){
			this.width=w+100;
		}
	    		 
		awardSheetGrid.editable="true";
		var params:Object=new Object();
		params["courseCode"]=courseCodeCombo.selectedLabel;
		params["startDate"]=semXml.root.(name==semesterCombo.selectedLabel).startDate;
		params["endDate"]=semXml.root.(name==semesterCombo.selectedLabel).endDate;
	    params["programCourseKey"]=programCourseKey;
	    params["entityId"]=entityXml.root.(name==entityNameCombo.selectedLabel).code;
	    params["employeeCode"]=employeeCode;
		params["displayType"]=displayType; //added by ankit
	    httpStatus.send(params);
	}
 
	public var popUpGrid:AwardBlankGrid;

	/*
	* function to create pop-up
	*/
	private function createPopup(dataArray:ArrayCollection):void{
		Mask.show("Wait....");
 		awardSheetCanvas.visible=false;
	 	popUpGrid=AwardBlankGrid(PopUpManager.createPopUp(this,AwardBlankGrid,true));
	 	popUpGrid.columnArray=componentAC;
	 	popUpGrid.studentDataArray=dataArray;
	 	
	 	popUpGrid.entityTypeValue.text=entityTypeName;
	 	popUpGrid.entityNameValue.text=entityName;
	 	popUpGrid.programValue.text=programName;
	 	popUpGrid.branchValue.text=branchName;
	 	popUpGrid.specializationValue.text=specializationName;
	 	popUpGrid.semesterValue.text=semesterName;
	 	popUpGrid.courseCodeValue.text=courseCode; 
	 	popUpGrid.courseNameValue.text=courseName;
	 	popUpGrid.approveFunction=approveRequest;
	 	popUpGrid.rejectFunction=rejectRequest;	
	 	popUpGrid.displayType=displayType;
	 	PopUpManager.centerPopUp(popUpGrid);	
	}
 
	public function getInWords(row:Object,col:AdvancedDataGridColumn):String {
		var num:String=row[col.dataField.slice(0,col.dataField.length-2)];
		if(num==null){
			return "";
		}
		else{
			return commonFunction.convertNumberToWord(int(num));
		}
	}
	
	public function showPendingList():void
	{
		pendingList=PendingRequest(PopUpManager.createPopUp(this,PendingRequest,true));
		pendingList.refFunc1=setButtonPressed;
		pendingList.refFunc2=setVariables;
		pendingList.dataArray=pendingAC;
		PopUpManager.centerPopUp(pendingList);
	}